﻿using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace XF.Common
{
    public class UpLoad
    {
        public Task<Tuple<bool, string, string>> UpLoadByUrl(string fileUrl, string fileName)
        {
            bool bResult = true;

            string strError = "";

            string ServerPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

            IOExtension.MakeDir(true, $@"{ServerPath}\UpLoad\MeetingRoomImg\");

            string Upload = $@"{ServerPath}\UpLoad\MeetingRoomImg\";

            if (!Directory.Exists(Upload))
            {
                Directory.CreateDirectory(Upload);
            }
            string FromFilePath = Path.Combine(fileUrl, fileName);

            FileStream FromStream = new FileStream(FromFilePath, FileMode.Open, FileAccess.Read);

            byte[] byteArray = new byte[FromStream.Length];

            if (FromStream.Length > 512000)
            {

                FromStream.Close();
                strError = "上传文件不能大于500kb";
                bResult = false;
                var tupp = new Tuple<bool, string, string>(bResult, strError, "");
                return Task.FromResult(tupp);

            }
            FromStream.Read(byteArray, 0, byteArray.Length);

            FromStream.Close();

            string ToFilePath = Path.Combine(Upload, fileName);

            FileStream ToStream = new FileStream(ToFilePath, FileMode.Create, FileAccess.Write);

            ToStream.Write(byteArray, 0, byteArray.Length);

            ToStream.Close();

            var tup = new Tuple<bool, string, string>(bResult, strError, "图片地址Url");

            return Task.FromResult(tup);
        }

        public Task<(bool, string, string,string)> FileUpload(System.Web.HttpPostedFile File,string type)
        {
            string Upload = "";
            string FilePath = "";
            string strError = "";
            bool bResult = true;
            var currentDate = DateTime.Now;
            string ServerPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            //IOExtension.MakeDir(true, $@"{ServerPath}\UpLoad\MeetingRoomImg\");

            if(type == "MinutesAnnex")
            {
                 Upload = $@"{ServerPath}/UpLoad/MinutesAnnex";
                 FilePath = "UpLoad/MinutesAnnex";
            }else if(type == "MeetingRoomImg")
            {
                Upload = $@"{ServerPath}/UpLoad/MeetingRoomImg";
                FilePath = "UpLoad/MeetingRoomImg";
            }
            else if(type == "System")
            {
                Upload = $@"{ServerPath}/UpLoad/System";
                FilePath = "UpLoad/System";
            }
            
            try
            {
                var filePath = $"/{currentDate:yyyyMMdd}/";

                //创建每日存储文件夹
                if (!Directory.Exists(Upload + filePath))
                {
                    Directory.CreateDirectory(Upload + filePath);
                }

                if (File != null)
                {
                    //文件后缀
                    //var fileExtension = Path.GetExtension(File.);//获取文件格式，拓展名

                    //判断文件大小
                    var fileSize = File.ContentLength;
                    if(type == "MinutesAnnex")
                    {
                        if (fileSize > 1024 * 1024*10) //10M TODO:(1mb=1024X1024b)
                        {

                            strError = "纪要附件不能大于10M";
                            bResult = false;

                            return Task.FromResult((bResult, strError, "", ""));
                        }
                    }
                    else if(type == "MeetingRoomImg")
                    {
                        if (fileSize > 1024 * 500) //500KB TODO:(1mb=1024X1024b)
                        {

                            strError = "会议室图片不能大于500kb";
                            bResult = false;

                            return Task.FromResult((bResult, strError, "", ""));
                        }
                    }
                    else if (type == "System")
                    {
                        if (fileSize > 1024 * 500) //500KB TODO:(1mb=1024X1024b)
                        {

                            strError = "上传文件不能大于500kb";
                            bResult = false;

                            return Task.FromResult((bResult, strError, "", ""));
                        }
                    }
                    

                    //保存的文件名称(以名称和保存时间命名)
                    var saveName = currentDate.ToString("HHmmss") + "_" + File.FileName;

                    //文件保存
                    using (var fs = System.IO.File.Create(Upload + filePath+ saveName))
                    {
                        File.InputStream.CopyTo(fs);
                        fs.Flush();
                    }

                    //完整的文件路径
                    var completeFilePath = Path.Combine(FilePath + filePath + saveName);


                    return Task.FromResult((bResult, strError, completeFilePath, saveName));
                }
                else
                {

                    return Task.FromResult((bResult, strError, "未检测到文件信息",""));
                }

            }
            catch (Exception ex)
            {
                bResult = false;
                strError = "上传异常：" + ex.ToString();

                return Task.FromResult((bResult, strError, "",""));
            }

        }

        /// <summary>
        /// 根据路径删除文件
        /// </summary>
        /// <param name="path"></param>
        public void DeleteFile(string path)
        {
            string ServerPath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            string a = ServerPath + "";
            FileAttributes attr = File.GetAttributes(path);
            if (attr == FileAttributes.Directory)
            {
                Directory.Delete(path, true);
            }
            else
            {
                File.Delete(path);
            }
        }
    }
}